package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.asl.constant.AslConstant;
import com.ev.framework.utils.R;
import com.ev.k3cloud.service.K3CloudService;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3DeptSynService;
import com.ev.k3cloudBusiness.vo.K3DeeSyncVO;
import com.ev.k3cloudBusiness.vo.K3DeptResultsVo;
import com.ev.k3cloudBusiness.vo.K3MaterialResultsVo;
import com.ev.system.dao.DeptDao;
import com.ev.system.domain.DeptDO;
import com.ev.system.service.DeptService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3DeptSynServiceImpl implements K3DeptSynService {

    @Autowired
    DeptDao deptDao;
    @Autowired
    K3CloudService k3CloudService;
    @Autowired
    DeptService deptService;
    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Override
    public  R DeptSyn() throws Exception
    {

        R dept=this.DeptSyn("dept");
        return dept;
    }
    private R DeptSyn(String Type) throws Exception {
        //查询芯软云部门
        List<DeptDO> deptDOList=deptService.listForAll();
        //调用K3Cloud部门单据查询接口查询启用的部门

        String materialResult=kingdeeMiddlewareService.DepartmentAll();
        K3DeeSyncVO<List<K3DeptResultsVo>> kingdeeSyncVO = new Gson().fromJson(materialResult,new TypeToken<K3DeeSyncVO<List<K3DeptResultsVo>>>(){}.getType());
        if(!AslConstant.ZERO.equals(kingdeeSyncVO.getCode()))
        {
            log.info(kingdeeSyncVO.getMsg());
            return  R.error(kingdeeSyncVO.getMsg());
        }
        List<K3DeptResultsVo> deptResultsVoList=kingdeeSyncVO.getData();
        if(deptResultsVoList.size() > 0)
        {
            // 本地部门代码
            List<Long> localIdList = deptDOList.stream().map(DeptDO::getDeptId).collect(Collectors.toList());
            // K3Cloud部门代码
            List<Long> remoteIdList = deptResultsVoList.stream().map(K3DeptResultsVo::getId).collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e)).collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains).collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if(deleteIdList.size()>0)
            {
                //批量删除
                List<DeptDO> deptDOS=deptDOList.stream().filter(e->deleteIdList.contains(e.getDeptId()) && e.getParentId()!=0).collect(Collectors.toList());

                for (DeptDO deptDO:deptDOS
                ) {
                    deptDO.setDelFlag(1);
                }
                if(deptDOS.size()>0)
                {
                    deptService.batchUpdate(deptDOS);
                    log.info("批量删除");
                }

            }
            if(updateIdList.size()>0)
            {
                //批量更新
                List<K3DeptResultsVo> depetResultsList = deptResultsVoList.stream().filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                List<DeptDO> depetDOListUpdate=deptDOList.stream().filter(e->updateIdList.contains(e.getDeptId())).collect(Collectors.toList());
                K3DeptResultsVo deptResultsVoResults;
                for (DeptDO deptDO:depetDOListUpdate
                ) {
                    deptResultsVoResults=depetResultsList.stream().filter(e->(deptDO.getDeptId().equals(e.getId()))).collect(Collectors.toList()).get(0);
                    //部门名称
                    deptDO.setName(deptResultsVoResults.getName());
                    //部门代码
                    deptDO.setDeptCode(deptResultsVoResults.getNumber());
                    //上级部门
                    deptDO.setParentId(1L);
                    deptDO.setDelFlag(0);
                }
                deptService.batchUpdate(depetDOListUpdate);
                log.info("批量更新");
            }
            if(remoteIdList.size()>0)
            {
                //批量插入
                List<K3DeptResultsVo> deptResultsVos= deptResultsVoList.stream().filter(e -> remoteIdList.contains(e.getId())).collect(Collectors.toList());
                List<DeptDO> deptDOListInsert= Lists.newArrayList();

                for (K3DeptResultsVo deptResult:deptResultsVos
                ) {

                    DeptDO deptdo=new DeptDO();
                    deptdo.setDeptId(deptResult.getId());
                    //部门名称
                    deptdo.setName(deptResult.getName());
                    //部门代码
                    deptdo.setDeptCode(deptResult.getNumber());
                    deptdo.setIdPath("/0/1/"+deptResult.getId()+"/");
                    //上级部门
                    deptdo.setParentId(1L);
                    deptdo.setDelFlag(0);
                    deptDOListInsert.add(deptdo);
                }
                deptService.batchSave(deptDOListInsert);
                log.info("批量新增");
            }
        }
        return R.ok();
    }
}
